package fuel

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"oil-station-backend/internal/model"
	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"
	"oil-station-backend/internal/utils"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderReq) (resp *types.Order, err error) {
	// 从上下文中获取用户ID
	userId, err := l.getUserIdFromContext()
	if err != nil {
		return nil, err
	}

	// 获取用户信息
	user, err := l.svcCtx.UserModel.FindById(userId)
	if err != nil {
		return nil, fmt.Errorf("用户不存在")
	}

	// 生成订单号
	orderNo := fmt.Sprintf("ORD%s%d", time.Now().Format("20060102150405"), userId)

	// 确定订单状态
	status := "pending" // 默认状态
	if req.Status == "paid" {
		status = "paid" // 如果指定为已支付，则设置为已支付状态
	}

	// 创建订单
	order := &model.Order{
		OrderNo:       orderNo,
		UserId:        userId,
		UserName:      user.Name,
		FuelType:      req.FuelType,
		FuelPrice:     req.FuelPrice,
		Volume:        req.Volume,
		PrepaidAmount: req.PrepaidAmount,
		Status:        status,
	}

	// 保存订单
	err = l.svcCtx.OrderModel.Create(order)
	if err != nil {
		return nil, err
	}

	// 转换为API响应格式
	return &types.Order{
		Id:            order.Id,
		OrderNo:       order.OrderNo,
		UserId:        order.UserId,
		UserName:      order.UserName,
		FuelType:      order.FuelType,
		FuelPrice:     order.FuelPrice,
		Volume:        order.Volume,
		PrepaidAmount: order.PrepaidAmount,
		Status:        order.Status,
		CreateTime:    order.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:    order.UpdateTime.Format("2006-01-02 15:04:05"),
	}, nil
}

func (l *CreateOrderLogic) getUserIdFromContext() (int64, error) {
    // 使用通用工具函数获取用户信息
    userId, _, err := utils.GetUserInfoFromContext(l.ctx)
    if err != nil {
        // 如果获取失败，尝试使用调试函数
        logx.Error("JWT claims not found in context, checking all context values:")
        l.debugContextValues()
        return 0, fmt.Errorf("未授权：无法从上下文中获取用户信息")
    }
    
    return userId, nil
}

// 调试函数：打印context中的值
func (l *CreateOrderLogic) debugContextValues() {
    // 尝试常见的JWT context keys，包括不同的大小写组合
    possibleKeys := []string{
        "jwt", "claims", "jwtUserId", "userId", "user", "jwtClaims", 
        "JWT", "auth", "token", "userinfo", "userInfo", "UserInfo", "USERINFO",
        "identity", "uid", "id", "ID", "Info", "info",
    }
    
    for _, key := range possibleKeys {
        if value := l.ctx.Value(key); value != nil {
            logx.Infof("Context key '%s' found with value: %+v (type: %T)", key, value, value)
            
            // 如果值是map类型，尝试查找id字段
            if mapValue, ok := value.(map[string]interface{}); ok {
                keys := getMapKeys(mapValue)
                logx.Infof("Map keys in '%s': %v", key, keys)
                
                // 尝试查找id字段（不同大小写）
                for _, idKey := range []string{"id", "Id", "ID"} {
                    if id, exists := mapValue[idKey]; exists {
                        logx.Infof("Found %s in map: %v (type: %T)", idKey, id, id)
                    }
                }
            }
            
            // 如果值是jwt.MapClaims类型
            if mapValue, ok := value.(jwt.MapClaims); ok {
                keys := getMapKeys(mapValue)
                logx.Infof("JWT MapClaims keys in '%s': %v", key, keys)
                
                // 尝试查找id字段（不同大小写）
                for _, idKey := range []string{"id", "Id", "ID"} {
                    if id, exists := mapValue[idKey]; exists {
                        logx.Infof("Found %s in JWT claims: %v (type: %T)", idKey, id, id)
                    }
                }
            }
        } else {
            logx.Infof("Context key '%s' not found", key)
        }
    }
    
    // 尝试获取请求头信息
    if r, ok := l.ctx.Value("r").(*http.Request); ok {
        authHeader := r.Header.Get("Authorization")
        logx.Infof("Authorization header: %s", authHeader)
        
        // 如果有Authorization头，尝试解析JWT
        if authHeader != "" && len(authHeader) > 7 {
            tokenString := authHeader[7:] // 去掉"Bearer "前缀
            logx.Infof("Token string: %s", tokenString)
            
            // 尝试解析token
            token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
                return []byte(l.svcCtx.Config.Auth.AccessSecret), nil
            })
            
            if err != nil {
                logx.Errorf("Error parsing JWT: %v", err)
            } else if token.Valid {
                logx.Infof("JWT is valid")
                if claims, ok := token.Claims.(jwt.MapClaims); ok {
                    logx.Infof("JWT claims: %+v", claims)
                }
            }
        }
    }
}

// 辅助函数：获取map的所有键
func getMapKeys(m interface{}) []string {
    var keys []string
    
    // 尝试不同类型的map
    if mapValue, ok := m.(map[string]interface{}); ok {
        for k := range mapValue {
            keys = append(keys, k)
        }
    } else if mapValue, ok := m.(jwt.MapClaims); ok {
        for k := range mapValue {
            keys = append(keys, k)
        }
    }
    
    return keys
}